//
//  DownloadController.swift
//  eBooks
//
//  Created by JunMing on 2019/11/7.
//  Copyright © 2019 赵俊明. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import FolioReaderKit

class DownloadController: EbookBaseController {
    private let disposeBag = DisposeBag()
    private var dataSource:Array<Model> = [Model]()
    open var bookName:String? {
        willSet {
            DispatchQueue.global().async {
                // 找到要插入的模型
                if let findModel = SQLHelper.share.fetchSigleModel(newValue!) {
                    self.dataSource = SQLHelper.share.fetchLocalDB(queryType: .deleteFalse)
                    
                    // 查一下是否已经存在了，存在的话就不再插入了
                    var isExist = false
                    for model in self.dataSource {
                        if model.fullname == findModel.fullname {
                            isExist = true
                            break
                        }
                    }
                    if !isExist {
                        self.dataSource.insert(findModel, at: 0)
                        SQLHelper.share.insertLocalDB(findModel)
                    }
                    DispatchQueue.main.async { self.tableView.reloadData() }
                }
            }
        }
    }
    private lazy var tableView:UITableView = {
        let tableView = UITableView(frame: self.view.bounds, style: UITableView.Style.plain)
        tableView.register(DownloadCell.self, forCellReuseIdentifier: "download")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorColor = UIColor.RGBA(230, 230, 230, 0.8)
        return tableView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "我的下载"
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.width.height.equalTo(view)
        }
        
        // 下载鉴权
        registerEvent(eventName: kEbooksBuyVipEventName, block: {[weak self] _ in
            // self?.buyAction(self?.view)
            self?.createRewardAD()
        }, next: false)
    }
}

extension DownloadController:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "download") as? DownloadCell
        if cell == nil {
            cell = DownloadCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "download")
        }
        cell!.downloadModel = dataSource[indexPath.row]
        cell!.downloadFails = { [weak self] model in
            self?.dataSource.remove(at: indexPath.row)
            tableView.reloadData()
            
            self?.showAlert("⬇️失败😭😭😭", "请下载其他资源", false, nil)
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = dataSource[indexPath.row]
        if !model.isdel {
            openEpubBooks(model)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64.0
    }
    
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCell.EditingStyle.delete {
            dataSource.remove(at: indexPath.row)
            let model = dataSource[indexPath.row]
            SQLHelper.share.deleteLocalDB(model)
            tableView.reloadData()
        }
    }
}

class DownloadCell: UITableViewCell,EbookDownloadProtocol {
    var downloadFails:((_ model:Model) -> Void)?
    fileprivate var cover = ImageLayerView()
    fileprivate var bookName = UILabel()
    fileprivate var bookSize = UILabel()
    fileprivate var deleted = UILabel()
    fileprivate var startDown = UIButton(type: UIButton.ButtonType.system)
    lazy var progressView: JMProgressCircleView = {
        return JMProgressCircleView()
    }()
    
    var downloadModel:Model? {
        willSet(newValue) {
            // 已下载且未删除，隐藏下载按钮
            if newValue!.isdel {
                startDown.setImage(UIImage(named: "startDownload"), for: UIControl.State.normal)
                startDown.isHidden = false
                deleted.text = "未下载"
            }else {
                print(newValue!.title() ?? "")
                startDown.isHidden = true
                deleted.text = ""
            }
            bookName.text = newValue?.title()
            bookSize.text = newValue?.sizeStr()
            if let url = newValue?.coverurl() { cover.loadImage(url: url) }
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        contentView.addSubview(cover)
        bookName.configLabel(font: UIFont.medium(15), tColor: UIColor.black)
        contentView.addSubview(bookName)
        
        bookSize.configLabel(font: UIFont.regular(13))
        contentView.addSubview(bookSize)
        
        deleted.configLabel(font: UIFont.regular(13))
        contentView.addSubview(deleted)
        
        contentView.addSubview(progressView)
        startDown.tintColor = UIColor.RGB(41, 41, 41)
        startDown.addTarget(self, action: #selector(startDownload(_:)), for: UIControl.Event.touchUpInside)
        contentView.addSubview(startDown)
        layout()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func startDownload(_ sender:UIButton) {
        let showView = fristShowView()
        if downloadModel!.isdel && downloadRight(superView: showView!) {
            downloadRun(model: downloadModel!) {[weak self] status in
                if status {
                    self?.bookSize.text = self?.downloadModel?.sizeStr()
                    self?.deleted.text = ""
                    sender.isHidden = true
                }else {
                    self?.downloadFails?((self?.downloadModel!)!)
                }
            }
        }
    }
    
    func layout() {
        cover.snp.makeConstraints { (make) in
            make.left.equalTo(contentView).offset(10)
            make.width.equalTo(44)
            make.top.equalTo(contentView).offset(5)
            make.bottom.equalTo(contentView).offset(-5)
        }
        
        bookName.snp.makeConstraints { (make) in
            make.left.equalTo(cover.snp_right).offset(10)
            make.top.equalTo(cover.snp_top).offset(5)
            make.right.equalTo(contentView.snp_right).offset(-60)
            make.height.equalTo(20)
        }
        
        bookSize.snp.makeConstraints { (make) in
            make.left.equalTo(cover.snp_right).offset(10)
            make.bottom.equalTo(cover.snp_bottom).offset(-5)
            make.height.equalTo(20)
        }
        
        deleted.snp.makeConstraints { (make) in
            make.left.equalTo(bookSize.snp_right).offset(10)
            make.bottom.equalTo(cover.snp_bottom).offset(-5)
            make.height.equalTo(20)
        }
        
        progressView.snp.makeConstraints { (make) in
            make.right.equalTo(contentView).offset(-10)
            make.centerY.equalTo(contentView.snp_centerY)
            make.height.width.equalTo(40)
        }
        
        startDown.snp.makeConstraints { (make) in
            make.right.equalTo(contentView).offset(-10)
            make.centerY.equalTo(contentView.snp_centerY)
            make.height.width.equalTo(40)
        }
    }
}
